<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\TaskAppModel;

class TaskDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $model = TaskAppModel::query();

        $model->when(checkIsHasField($params,'task_id'),function ($query)use ($params){
            $query->where('task_id',$params['task_id']);
        });

        $model->when(checkIsHasField($params,'show'),function ($query)use ($params){
            $query->where('show',$params['show']);
        });

        return $model->orderByDesc('created_at');
    }


    /**
     * @throws SysExceptions
     */
    public static function add($params = []){
        if(self::builder_query()->create($params) === false){
            self::error('添加失败');
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function edit($params = []){
        if(self::builder_query(['task_id'=>self::deleteParamId($params,'task_id')])->update(self::filterFields($params,new TaskAppModel())) === false){
            self::error('修改失败');
        }
    }

    public static function pages(array $params)
    {
        return self::builder_query($params)->paginate();
    }

    public static function info(array $params)
    {
        return self::builder_query($params)->first()->toArray();
    }

    public static function delete(array $all)
    {
        if (self::builder_query(['task_id'=>$all['id']])->delete() === false){
            self::error('删除失败');
        }
    }

    public static function all(array $params)
    {
        return self::builder_query($params)->get();
    }
}
